from .notification_service import send_system_notification
from ..repositories import users_repository
from ..repositories.users_repository import get_user_by_username, get_user_by_phone, add_user
from ..utils.password_utils import encrypt_password, decrypt_password
import asyncio
import re

async def validate_register_data(username, password, phone, verify_code):
    """
    验证注册数据
    :param username: 用户名
    :param password: 密码
    :param phone: 手机号
    :param verify_code: 验证码
    :return: (bool, str) - (验证是否通过, 错误信息)
    """
    # 验证用户名：4-16位字母数字
    if not username or not (4 <= len(username) <= 16) or not username.isalnum():
        return False, "用户名必须是4-16位字母或数字的组合"
        
    # 验证密码：6-16位字母数字
    if not password or not (6 <= len(password) <= 16) or not password.isalnum():
        return False, "密码必须是6-16位字母或数字的组合"
        
    # 验证手机号：11位数字
    if not re.match(r'^1[3-9]\d{9}$', phone):
        return False, "请输入有效的11位手机号码"
    
    # 验证验证码：4位数字
    if not verify_code or not verify_code.isdigit() or len(verify_code) != 4:
        return False, "验证码必须是4位数字"
        
    return True, ""

async def register(username, password, phone, verify_code):
    """
    注册账号
    :param username: 用户名
    :param password: 密码
    :param phone: 手机号
    :param verify_code: 验证码
    :return: 注册结果
    """
    # 1. 验证输入数据
    is_valid, error_message = await validate_register_data(username, password, phone, verify_code)
    if not is_valid:
        return {"code": 1000, "message": error_message}

    # 从数据库获取有效验证码
    valid_code = await users_repository.get_valid_code(phone)
    if not valid_code:
        return {"code": 1003, "message": "验证码已过期或不存在"}

    if decrypt_password(valid_code['code']) != verify_code:
        return {"code": 1003, "message": "验证码错误"}

    # 3. 并发检查用户名和手机号是否存在
    user_name = get_user_by_username(username)
    user_phone = get_user_by_phone(phone)
    existing_user, existing_phone = await asyncio.gather(user_name, user_phone)
    
    if existing_user:
        return {"code": 1001, "message": "用户名已存在"}
    if existing_phone:
        return {"code": 1002, "message": "手机号已存在"}

    # 4. 加密密码并添加用户
    encrypted_password = encrypt_password(password)
    if not await add_user(username, encrypted_password, phone):
        return {"code": 1004, "message": "注册失败，请稍后重试"}

    return {"code": 0, "message": "注册成功"}
